package android.olsson.apk;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.olsson.apk.interfaces.IBeverage;
import android.olsson.apk.interfaces.IInternetHandler;
import android.olsson.apk.interfaces.IFileHandler;
import android.util.Log;

public class InternetHandler implements IInternetHandler {
	private final String TAG = "DATABASE_HANDLER_ERROR";
	private String result;
	private HttpClient client;
	private HttpPost post;
	private ArrayList<NameValuePair> nameValuePairs;
	private HttpResponse response;
	private HttpEntity entity;
	private BufferedReader bufferedReader;
	private InputStream inputStream;
	private StringBuilder stringBuilder;
	private ArrayList<IBeverage> beverageList;

	public InternetHandler() {
		result = "";
		client = new DefaultHttpClient();

		// The link to the PHP-script that retrieves the database
		post = new HttpPost("http://www.plast.netne.net/db.php");

		beverageList = new ArrayList<IBeverage>();

		// To send values to the server code, put them in
		// nameValuePairs as BasicNameValuePairs.
		nameValuePairs = new ArrayList<NameValuePair>();
	}

	@Override
	public void downloadDatabase() {
		try {
			post.setEntity((new UrlEncodedFormEntity(nameValuePairs)));
			response = client.execute(post);
			entity = response.getEntity();
			inputStream = entity.getContent();
		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, e.toString());
		} catch (ClientProtocolException e) {
			Log.e(TAG, e.toString());
		} catch (IOException e) {
			Log.e(TAG, e.toString());
		}

		try {
			bufferedReader = new BufferedReader(new InputStreamReader(
					inputStream, "utf-8"));
			stringBuilder = new StringBuilder();
			String line = null;

			while ((line = bufferedReader.readLine()) != null) {
				stringBuilder.append(line + "\n");
			}
			inputStream.close();

			result = stringBuilder.toString();

		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, e.toString());
		} catch (IOException e) {
			Log.e(TAG, e.toString());
		}

		decodeDatabaseInfo();
		writeDatabaseToFile();
	}

	private void decodeDatabaseInfo() {
		try {
			JSONArray jsonArray = new JSONArray(result);

			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				if (!jsonObject.getString("namn").equalsIgnoreCase("null")) {
					String name = jsonObject.getString("namn");
					String type = jsonObject.getString("varugrupp");

					// Set the first letter to upper case. (Maybe not needed)
					type = type.toLowerCase();
					type = type.substring(0, 1).toUpperCase()
							+ type.substring(1);
					// -----------------------------------

					float price = Util.getPriceAsFloat(jsonObject
							.getString("prisinklmoms"));
					float volume = Util.getVolumeAsFloat(jsonObject
							.getString("volymiml"));
					float alcohol = Util.getAlcoholAsFloat(jsonObject
							.getString("alkoholhalt"));

//					float apk = (alcohol * volume) / (price * 100);
					float apk = (float) (Math.round(((alcohol * volume) / (price * 100)) * 100.0)/100.0);

					beverageList.add(new Beverage(name, type, volume, alcohol,
							price, apk));
				}
			}
		} catch (JSONException e) {
			Log.e(TAG, e.toString());
		}
	}

	private void writeDatabaseToFile() {
		IFileHandler fileHandler = new FileHandler();
		fileHandler.writeToFile(Util
				.getSortedBeverageList("Alla", beverageList));
	}
}
